package com.studerb.view.server;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import net.miginfocom.layout.LC;
import net.miginfocom.swing.MigLayout;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.net.nntp.NNTP;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.studerb.model.Server;
import com.studerb.service.interfaces.IServerService;

public class MasterServerPane extends JPanel implements ActionListener, ItemListener{
    private Logger logger = Logger.getLogger(MasterServerPane.class);
    private final static int DEFAULT_CONNECTIONS = 1;
    @Autowired IServerService serverService;
    private JLabel hostLabel; 
    private JLabel portLabel; 
    private JLabel connectionsLabel; 
    private JLabel userNameLabel;
    private JLabel passwordLabel;

    private JTextField hostField; 
    private JTextField portField;
    private JTextField connectionsField; 
    private JTextField userNameField;
    private JPasswordField passwordField;
    private JCheckBox authRequiredCB;
    
    private JButton saveButton;
    
    public void init(){
        initComponents();
        setMasterServer();
    }

    public void initComponents(){
        
        this.setLayout(new MigLayout(new LC().insets("30")));

        hostLabel = new JLabel("Host");
        add(hostLabel);
        hostField = new JTextField(30);
        add(hostField, "wrap");
        
        portLabel = new JLabel("Port");
        add(portLabel);
        portField = new JTextField(5);
        add(portField, "wrap");
        
        connectionsLabel = new JLabel("Number of Connections");
        add(connectionsLabel);
        connectionsField = new JTextField(5);
        add(connectionsField, "wrap");

        JLabel authRequiredLabel = new JLabel("Authorization");
        add(authRequiredLabel);
        authRequiredCB= new JCheckBox("Required");
        authRequiredCB.addItemListener(this);
        add(authRequiredCB, "wrap");
        
        userNameLabel = new JLabel("User");
        add(userNameLabel);
        userNameField = new JTextField(30);
        add(userNameField, "wrap");
        
        passwordLabel = new JLabel("Password");
        add(passwordLabel);
        passwordField = new JPasswordField(30);
        add(passwordField, "wrap");
        
        saveButton = new JButton("Save");
        saveButton.addActionListener(this);
        add(saveButton, "wrap");
        
    }

    @Override public void actionPerformed(ActionEvent e) {
        if (e.getSource() == saveButton){
            updateServer();
        }
    }
    
    private void updateServer(){
        try {
            Server master = serverService.getMasterServer();
            if(master == null){
                master = new Server();
            }
            master.setMaster(true);
            master.setHost(hostField.getText());
            master.setPort(Integer.parseInt(portField.getText()));
            master.setConnections(Integer.parseInt(connectionsField.getText()));
            master.setAuthRequired(authRequiredCB.isSelected());
            master.setUserName(userNameField.getText());
            master.setPassword(new String(passwordField.getPassword()));
            if(serverService.isMasterServerDefined()){
                serverService.updateServer(master);
            }
            else {
                serverService.addServer(master);
            }
            JOptionPane.showMessageDialog(this, "Successfully Updated Master Server");
        }
        catch(Exception e){
            logger.warn(ExceptionUtils.getRootCauseMessage(e));
            JOptionPane.showMessageDialog(this, "Error saving Server: " + ExceptionUtils.getMessage(e)); 
        }
    }
    
    private void setMasterServer(){
        Server master = serverService.getMasterServer();
        if(master == null){
            portField.setText(String.valueOf(NNTP.DEFAULT_PORT));
            connectionsField.setText(String.valueOf(DEFAULT_CONNECTIONS));
            authRequiredCB.setSelected(true);
        }
        else {
            hostField.setText(master.getHost());
            portField.setText(String.valueOf(master.getPort()));
            connectionsField.setText(String.valueOf(master.getConnections()));
            authRequiredCB.setSelected(master.isAuthRequired());
            userNameField.setText(master.getUserName());
            passwordField.setText(master.getPassword());
        }
    }

    @Override public void itemStateChanged(ItemEvent e) {
        if(e.getItemSelectable() == authRequiredCB){
            //TODO more validation for when authrequired changes
            //logger.debug("authRequired state change: " + e.getStateChange());
        }
        
    }
}
